package com.ys.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.amazonorder.TbBaseinfoSpcz;
import com.ys.entity.business.*;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.storage.TccAssemblyMaintain;
import com.ys.entity.sys.YsCol;
import com.ys.enume.business.TpProductMaterialEnum;
import com.ys.mapper.business.*;
import com.ys.mapper.storage.TccAssemblyMaintainMapper;
import com.ys.service.business.TpBoutiqueService;
import com.ys.service.business.TpProductActiveService;
import com.ys.util.CheckUtil;
import com.ys.util.RandomUtil;
import com.ys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Listing库
 */
@Service("tpProductActiveService")
public class TpProductActiveServiceImpl implements TpProductActiveService {
	
	@Autowired
	private TpProductActiveMapper tpProductActiveMapper;

	@Autowired
	private TpProductBasisMapper tpProductBasisMapper;

	@Autowired
	private DiySqlMapper diySqlMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private BusinessMapper businessMapper;

	@Autowired
	private TpProductMaterialMapper tpProductMaterialMapper;


	@Autowired
	private TpBoutiqueService tpBoutiqueService;

	@Autowired
	private TpProductBasisComponentMapper tpProductBasisComponentMapper;


	@Autowired
	private TpProductActiveComponentMapper tpProductActiveComponentMapper;

	@Autowired
	private TccAssemblyMaintainMapper tccAssemblyMaintainMapper;


	@Override
	public R add(Map<String, Object> params) {
		
		String code = params.get("code").toString();
		if (code == null ) {
			return R.error("商品编码不能为空");
		} else if (new TpProductActive().setCode(code).count() > 0) {
			return R.error("该商品已存在");
		}
		
		TpProductActive entity = JSON.parseObject(JSON.toJSONString(params), TpProductActive.class);
		tpProductActiveMapper.insert(entity);
		return R.ok(AddDto.closeAndReload());
	}
	

	/**
	 * 删除
	 * @operateCompanyId operateCompanyId
	 * @return
	 */
	@Override
	@Transactional
	public R deleteTpProductActive(Map<String, Object> params) {
		String[] strs = params.get("list").toString().split(",");
		for(int i=0,len=strs.length;i<len;i++){
			diySqlMapper.deleteTpProductActive(Long.valueOf(strs[i]));
		}
		return R.ok(EditDto.closeAndReload());
	}

	@Override
	public R edit(Map<String, Object> params) {
		// 验证编码
		String code = params.get("code").toString();
		if (new TpProductActive().setCode(code).where("A.Id != '" + params.get("id").toString() + "'").count() > 0) {
			return R.error("商品已存在");
		}
		TpProductActive entity = JSON.parseObject(JSON.toJSONString(params), TpProductActive.class);
		tpProductActiveMapper.update(entity);
		return R.ok(EditDto.closeAndReload());
	}



	/**
	 * 修改，同时修改相关库信息
	 */
	@Override
	public R editAndCorrelation(Map<String, Object> params) throws Exception{

		// 验证编码
		String code = params.get("code").toString();
		if (new TpProductActive().setCode(code).where("A.Id != '" + params.get("id").toString() + "'").count() > 0) {
			return R.error("商品已存在");
		}

		//Listing库修改
		TpProductActive entity = JSON.parseObject(JSON.toJSONString(params), TpProductActive.class);
		if(entity.getCodeHs()!=null)entity.setCodeHs(entity.getCodeHs().trim());
		tpProductActiveMapper.update(entity);
		//同步更新商品库信息
		TpProductBasis tpProductBasis = setProductBasis(entity);
		tpProductBasisMapper.update(tpProductBasis);

		if(params.get("materialId")!=null && !"".equals(params.get("materialId"))){
			// 清除旧的商品材质
			businessMapper.deleteTrueTpProductMaterial(entity.getCode(), TpProductMaterialEnum.Type.TP_ProductBasis.value);
			businessMapper.deleteTrueTpProductMaterial(entity.getCode(), TpProductMaterialEnum.Type.TP_ProductActive.value);
//			String materialCnArr = params.get("materialCn").toString();
//			String materialEnArr = params.get("materialEn").toString();
			String materialIdArr = params.get("materialId").toString();
			// 逐条新增商品材质
			//String[] materialCnJA = materialCnArr.split(",");
			//String[] materialEnJA = materialEnArr.split(",");
			String[] materialIdJA = materialIdArr.split(",");
			for (int j = 0; j < materialIdJA.length; j++) {
				if(materialIdJA[j]!=null && !"".equals(materialIdJA[j])){
					Integer type = TpProductMaterialEnum.Type.TP_ProductBasis.value;
					String productCode = entity.getCode();
					Long materialId = Long.valueOf(materialIdJA[j]);
					TbBaseinfoSpcz tbBaseinfoSpcz = new TbBaseinfoSpcz().setId(materialId).queryFirst();
					//String materialNameCn = materialCnJA[j];
					//String materialNameEn = materialEnJA[j];
					String materialNameCn = tbBaseinfoSpcz.getMaterialCn();
					String materialNameEn = tbBaseinfoSpcz.getMaterialEn();
					TpProductMaterial tpProductMaterial = TpProductMaterial.tpProductMaterial(type, productCode, materialId, materialNameCn, materialNameEn, 1);
					tpProductMaterialMapper.insert(tpProductMaterial);

					type = TpProductMaterialEnum.Type.TP_ProductActive.value;
					tpProductMaterial = TpProductMaterial.tpProductMaterial(type, productCode, materialId, materialNameCn, materialNameEn, 1);
					tpProductMaterialMapper.insert(tpProductMaterial);
				}

			}
		}

		//修改精品库是否生效
		if(entity.getVsfJp()!=null){
			addTpBoutiqueAndUpdateIsEffect(entity);
		}
		return R.ok(EditDto.closeAndReload());
	}

	//新增精品库信息
	public void addTpBoutiqueAndUpdateIsEffect(TpProductActive entity)throws Exception {
		int status = 0;
		TpBoutique tpBoutique = new TpBoutique();
		if(entity.getVsfJp().equals("是")){
			status = 1;
			TpProductActive tpProductActive = new TpProductActive().setId(entity.getId()).queryFirst();
			if(tpProductActive!=null){
				TpBoutique hasTpBoutique = new TpBoutique().setCode(tpProductActive.getCode()).queryFirst();
				if(hasTpBoutique==null){
					//新增精品
					TpBoutique tpBoutiqueNew = new TpBoutique();
					tpBoutiqueNew.setCode(tpProductActive.getCode());
					tpBoutiqueNew.setName(tpProductActive.getName());
					tpBoutiqueNew.setCodeMerge(tpProductActive.getCodeMerge());
					tpBoutiqueNew.setBoutiqueIsEffect(0);
					tpBoutiqueNew.setAuthType(0);
					if(tpProductActive.getImg()!=null && !"".equals(tpProductActive.getImg())){
						tpBoutique.setCoverImg(tpProductActive.getImg());
					}
					tpBoutiqueService.add(tpBoutiqueNew);
				}
			}
		}else {
			tpBoutique.setBoutiqueIsEffect(0);//精品是否生效(0未生效，1已生效)
		}
		tpBoutique.setStatus(status);

		tpBoutique.setCode(entity.getCode());//商品编码
		if(entity.getCodeMerge()!=null && !"".equals(entity.getCodeMerge())){
			tpBoutique.setCodeMerge(entity.getCodeMerge());//合并商品编码
		}
		diySqlMapper.updateTpBoutiqueBoutiqueIsEffect(tpBoutique);//通过商品编码修改精品库中精品是否生效(0未生效，1已生效)信息
	}

	/**
	 * 参数验证
	 */
	@Override
	public String checkParams(Map<String, Object> params,Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				//.setFormEditRequired(1)//编辑必填
				.setOrderby("A.SortNo ASC")
				.queryList();

		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TP_ProductActive",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		String decimalCount = "2";
		for(YsCol item:listField){
			if(item.getCode().equals("sizeLength") || item.getCode().equals("sizeWidth") || item.getCode().equals("sizeHeight")
					|| item.getCode().equals("sizeWeight")){
				if(params.get(item.getCode())!=null && !checkUtil.isDecimal(params.get(item.getCode()).toString(),decimalCount)){
					backMsg = item.getName()+"应为"+decimalCount+"位小数！";
				}
			}
		}
		//合并商品编码验证，是否在Listening库中存在该商品编码
		if(params.get("codeMerge")!=null){
			TpProductActive tpProductActive = new TpProductActive().setCode(params.get("codeMerge").toString()).queryFirst();
			if(tpProductActive==null){
				backMsg = "该合并商品编码在Listing库中找不到对应的商品编码！";
			}
		}

		//验证
		if(params.get("vsfJp")!=null){
			if (params.get("vsfJp").equals("是")){
				if (params.get("commodityPl") == null || "".equals(params.get("commodityPl"))){
					backMsg = "该商品属性是精品,商品品类不允许为空!";
				}
			}
		}
		//验证
		if(params.get("ageRange")!=null && !params.get("ageRange").equals("")){
			String regex ="^[\\w\\d]+\\S";
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher =pattern.matcher(params.get("ageRange").toString());
			if (!matcher.find()){
				backMsg = "年龄范围只允许英文字母加数字!";
			}
		}

		//验证商品属性是否一致
		if(params.get("commodityProperty")!=null && params.get("vsfJp")!=null && params.get("isSuperior")!=null){
			if(params.get("commodityProperty").equals("新品")){
				if(params.get("vsfJp").equals("是")){
					backMsg = "商品属性为"+params.get("commodityProperty")+"时精品属性应为否！";
				}
				if(params.get("isSuperior").equals("是")){
					backMsg = "商品属性为"+params.get("commodityProperty")+"时优品属性应为否！";
				}
			}else if(params.get("commodityProperty").equals("优品")){
				if(params.get("vsfJp").equals("是")){
					backMsg = "商品属性为"+params.get("commodityProperty")+"时精品属性应为否！";
				}
				if(params.get("isSuperior").equals("否")){
					backMsg = "商品属性为"+params.get("commodityProperty")+"时优品属性应为是！";
				}
			}else if(params.get("commodityProperty").equals("变体")){
				if(params.get("vsfJp").equals("是")){
					backMsg = "商品属性为"+params.get("commodityProperty")+"时精品属性应为否！";
				}
				if(params.get("isSuperior").equals("是")){
					backMsg = "商品属性为"+params.get("commodityProperty")+"时优品属性应为否！";
				}
			}else if(params.get("commodityProperty").equals("精品")){
				if(params.get("vsfJp").equals("否")){
					backMsg = "商品属性为"+params.get("commodityProperty")+"时精品属性应为是！";
				}
				if(params.get("isSuperior").equals("是")){
					backMsg = "商品属性为"+params.get("commodityProperty")+"时优品属性应为否！";
				}
			}else{
				backMsg = "请选择的商品属性！";
			}

		}
		return backMsg;
	}


	/**
	 * 去除多余参数，只保留有权限编辑的参数
	 */
	@Override
	public Map<String, Object> removeSurplusParams(Map<String, Object> params,Long menuId,boolean hasSonList) throws Exception {
		Map<String, Object> paramsNew = new HashMap<>();
		//获取pc编辑只读字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				//.setFormEditReadonly(1)//编辑只读
				.queryList();
		paramsNew.put("id",params.get("id"));//id必需
		paramsNew.put("code",params.get("code"));//商品编码必需
		if(hasSonList){//如果有权限修改子表信息，则保留
			paramsNew.put("subData",params.get("subData"));
		}
		if(listField!=null && listField.size()>0){
			for (String key : params.keySet()) {
				boolean isReadOnly = false;//是否只读
				for (YsCol item : listField) {
					if(item.getCode().equals(key)  && item.getFormEditReadonly()!=null && item.getFormEditReadonly()==1){
						isReadOnly = true;
					}
				}
				if(!isReadOnly){//如果非只读，即是有权限修改的
					paramsNew.put(key,params.get(key));
				}
			}
		}
		if (params.get("materialEn") != null
		){
			paramsNew.put("materialEn",params.get("materialEn") );
		}
		return paramsNew;
	}

	//批量调整精品库的运营公司编码
	@Override
	public R updateVgsbmByList(List<String> codeList,String vgsbm) {
		//验证运营公司编码是否存在
		int count = new ThrOperateCompanyApply().where("A.Vgsbm = '"+vgsbm+"'").count();
		if(count>0){
			//循环修改公司编码
			if(codeList!=null && codeList.size()>0){
				for(String code:codeList){
					diySqlMapper.updateProductActiveAndBasis(code,vgsbm);
				}
			}
		}else{
			return R.error("填写的公司编码不存在！");
		}
		return R.ok();
	}


	//商品复制
	@Override
	public R copyGoods(List<String> codeList) throws Exception{

		for(String code:codeList){
			TpProductActive tpProductActive = new TpProductActive().setCode(code).queryFirst();
			if(tpProductActive!=null && tpProductActive.getId()!=null){
				TpProductBasis entity =  setProductBasisComm(tpProductActive,new TpProductBasis());
				String codeByNew = code+"N";
				int isCopy = new TpProductBasis().setCode(codeByNew).count();
				if(isCopy<=0){
					entity.setCode(codeByNew);
					entity.setStatus(1);
					//新增母表信息
					tpProductBasisMapper.insert(entity);
					//新增子表信息
					List<TpProductBasisComponent> sonList = new TpProductBasisComponent().setPcode(code).queryList();
					if(sonList!=null && sonList.size()>0){
						for(TpProductBasisComponent sonItem:sonList){
							sonItem.setPcode(codeByNew);
							String sonCode = sonItem.getCode();
							String[] codeArr = sonCode.split("-");
							String sonCodeByNew = sonCode+"N";
							if(codeArr.length>1){
								sonCodeByNew = codeArr[0]+"N"+"-"+codeArr[1];
							}
							sonItem.setCode(sonCodeByNew);
							tpProductBasisComponentMapper.insert(sonItem);
						}

					}
				}

				//复制listing库信息
				int isCopyByActive = new TpProductActive().setCode(codeByNew).count();
				if(isCopyByActive<=0){
					tpProductActive.setCode(codeByNew);
					tpProductActiveMapper.insert(tpProductActive);
					//新增子表信息
					List<TpProductActiveComponent> sonList = new TpProductActiveComponent().setPcode(code).queryList();
					if(sonList!=null && sonList.size()>0){
						for(TpProductActiveComponent sonItem:sonList){
							sonItem.setPcode(codeByNew);
							String sonCode = sonItem.getCode();
							String[] codeArr = sonCode.split("-");
							String sonCodeByNew = sonCode+"N";
							if(codeArr.length>1){
								sonCodeByNew = codeArr[0]+"N"+"-"+codeArr[1];
							}
							sonItem.setCode(sonCodeByNew);
							tpProductActiveComponentMapper.insert(sonItem);
						}

					}

					//修改精品库是否生效
					if(tpProductActive.getVsfJp()!=null){
						addTpBoutiqueAndUpdateIsEffect(tpProductActive);
					}


					//新增组装方案维护
					TccAssemblyMaintain tccAssemblyMaintain = new TccAssemblyMaintain();
					tccAssemblyMaintain.setGuid(RandomUtil.getGUID());
					tccAssemblyMaintain.setName("ZZFA001");
					tccAssemblyMaintain.setWay("人工");
					tccAssemblyMaintain.setProductName(tpProductActive.getName());
					tccAssemblyMaintain.setProductID(codeByNew);
					tccAssemblyMaintain.setLength(new BigDecimal("0.1"));
					tccAssemblyMaintain.setWidth(new BigDecimal("0.1"));
					tccAssemblyMaintain.setWidth(new BigDecimal("0.1"));
					tccAssemblyMaintain.setWeight(new BigDecimal("0.1"));
					tccAssemblyMaintain.setCreateUser(entity.getCreateChangeId());
					tccAssemblyMaintain.setUpdateUser(entity.getCreateChangeId());
					tccAssemblyMaintain.setProductLength(BigDecimal.ZERO);
					tccAssemblyMaintain.setProductWeight(BigDecimal.ZERO);
					tccAssemblyMaintain.setProductWidth(BigDecimal.ZERO);
					tccAssemblyMaintain.setProductHeight(BigDecimal.ZERO);
					tccAssemblyMaintain.setStatus(1);
					tccAssemblyMaintainMapper.insert(tccAssemblyMaintain);



				}

			}

		}

		return R.ok();
	}



	//设置商品库字段
	public TpProductBasis setProductBasis(TpProductActive tpProductActive){
		//根据code获取原有商品库数据
		TpProductBasis entity = new TpProductBasis().setCode(tpProductActive.getCode()).queryFirst();
		entity = setProductBasisComm(tpProductActive,entity);
		return entity;
	}



	//设置商品库字段
	public TpProductBasis setProductBasisComm(TpProductActive tpProductActive,TpProductBasis entity){
		//填充数据
		if(checkUtil.isNotNullByObject(tpProductActive.getImg()))entity.setImg(tpProductActive.getImg());//商品图片
		if(checkUtil.isNotNullByObject(tpProductActive.getCodeHs()))entity.setCodeHs(tpProductActive.getCodeHs());//海关编码
		if(checkUtil.isNotNullByObject(tpProductActive.getSizeLength()))entity.setSizeLength(tpProductActive.getSizeLength());//商品长度（cm）
		if(checkUtil.isNotNullByObject(tpProductActive.getSizeWidth()))entity.setSizeWidth(tpProductActive.getSizeWidth());//商品宽度（cm）
		if(checkUtil.isNotNullByObject(tpProductActive.getSizeHeight()))entity.setSizeHeight(tpProductActive.getSizeHeight());//商品高度（cm）
		if(checkUtil.isNotNullByObject(tpProductActive.getSizeWeight()))entity.setSizeWeight(tpProductActive.getSizeWeight());//商品重量（g）
		if(checkUtil.isNotNullByObject(tpProductActive.getName()))entity.setName(tpProductActive.getName());//商品名称
		if(checkUtil.isNotNullByObject(tpProductActive.getNameId()))entity.setNameId(tpProductActive.getNameId());//商品品名（中）
//		if(checkUtil.isNotNullByObject(tpProductActive.getNameEn()))entity.setNameEn(tpProductActive.getNameEn());//商品品名（英）
		if(checkUtil.isNotNullByObject(tpProductActive.getNameUnitId()))entity.setNameUnitId(tpProductActive.getNameUnitId());//商品单位
//		if(checkUtil.isNotNullByObject(tpProductActive.getMaterialId()))entity.setMaterialId(tpProductActive.getMaterialId());//商品材质（中）
//		if(checkUtil.isNotNullByObject(tpProductActive.getMaterialEn()))entity.setMaterialEn(tpProductActive.getMaterialEn());//商品材质（英）
		if(checkUtil.isNotNullByObject(tpProductActive.getUsageId()))entity.setUsageId(tpProductActive.getUsageId());//商品用途（中）
//		if(checkUtil.isNotNullByObject(tpProductActive.getUsageEn()))entity.setUsageEn(tpProductActive.getUsageEn());//商品用途（英）
		if(checkUtil.isNotNullByObject(tpProductActive.getCombination()))entity.setCombination(tpProductActive.getCombination());//商品组合
		if(checkUtil.isNotNullByObject(tpProductActive.getLinkIn()))entity.setLinkIn(tpProductActive.getLinkIn());//采购链接
//		if(checkUtil.isNotNullByObject(tpProductActive.getVgsMc()))entity.setVgsMc(tpProductActive.getVgsMc());//公司名称
//		if(checkUtil.isNotNullByObject(tpProductActive.getVgsJc()))entity.setVgsJc(tpProductActive.getVgsJc());//公司简称
		if(checkUtil.isNotNullByObject(tpProductActive.getVgsBm()))entity.setVgsBm(tpProductActive.getVgsBm());//公司编码
		//if(checkUtil.isNotNullByObject(tpProductActive.getVtitle()))entity.setVtitle(tpProductActive.getVtitle());//商品库无***商品标题
//		if(checkUtil.isNotNullByObject(tpProductActive.getVspLm1()))entity.setVspLm1(tpProductActive.getVspLm1());//商品类目
		//if(checkUtil.isNotNullByObject(tpProductActive.getVspMd1()))entity.setVspMd1(tpProductActive.getVspMd1());//商品库无***商品卖点 1-5
		//if(checkUtil.isNotNullByObject(tpProductActive.getVspGjz()))entity.setVspGjz(tpProductActive.getVspGjz());//商品库无***商品关键词
		//if(checkUtil.isNotNullByObject(tpProductActive.getVspZt()))entity.setVspZt(tpProductActive.getVspZt());//商品库无***商品主图1-2
		//if(checkUtil.isNotNullByObject(tpProductActive.getVspCct()))entity.setVspCct(tpProductActive.getVspCct());//商品库无***商品尺寸图
		//if(checkUtil.isNotNullByObject(tpProductActive.getVspXjt1()))entity.setVspXjt1(tpProductActive.getVspXjt1());//商品库无***商品细节图1-3
		//if(checkUtil.isNotNullByObject(tpProductActive.getVspCjt1()))entity.setVspCjt1(tpProductActive.getVspCjt1());//商品库无***商品场景图1-3
		if(checkUtil.isNotNullByObject(tpProductActive.getLinkJp()))entity.setLinkJp(tpProductActive.getLinkJp());//竞品链接(英国)
		//if(checkUtil.isNotNullByObject(tpProductActive.getLinkJPUS()))entity.setLinkJPUS(tpProductActive.getLinkJPUS());//商品库无***竞品链接(美国)
		if(checkUtil.isNotNullByObject(tpProductActive.getCodeMerge()))entity.setCodeMerge(tpProductActive.getCodeMerge());//合并商品编码
		if(checkUtil.isNotNullByObject(tpProductActive.getVsfJp()))entity.setVsfJp(tpProductActive.getVsfJp());//精品属性
		if(checkUtil.isNotNullByObject(tpProductActive.getIsSuperior()))entity.setIsSuperior(tpProductActive.getIsSuperior());//是否优品(是/否)
		if(checkUtil.isNotNullByObject(tpProductActive.getImg1()))entity.setImg1(tpProductActive.getImg1());//验收图片1
		if(checkUtil.isNotNullByObject(tpProductActive.getImg2()))entity.setImg2(tpProductActive.getImg2());//验收图片2
		//if(checkUtil.isNotNullByObject(tpProductActive.getSpMcGg()))entity.setSpMcGg(tpProductActive.getSpMcGg());//商品库无***商品名称及规格型号
		//if(checkUtil.isNotNullByObject(tpProductActive.getDeclarationElements()))entity.setDeclarationElements(tpProductActive.getDeclarationElements());//商品库无***报关要素
		if(checkUtil.isNotNullByObject(tpProductActive.getIsUsable()))entity.setIsUsable(tpProductActive.getIsUsable());//商品状态
		if(checkUtil.isNotNullByObject(tpProductActive.getCommodityLmId()))entity.setCommodityLmId(tpProductActive.getCommodityLmId());//商品类目id
		if(checkUtil.isNotNullByObject(tpProductActive.getCommodityPlId()))entity.setCommodityPlId(tpProductActive.getCommodityPlId());//商品品类id
		if(checkUtil.isNotNullByObject(tpProductActive.getCommodityProperty()))entity.setCommodityProperty(tpProductActive.getCommodityProperty());//商品属性
		if(checkUtil.isNotNullByObject(tpProductActive.getCommodityRemark()))entity.setCommodityRemark(tpProductActive.getCommodityRemark());//商品备注

		return entity;
	}



}
